<template>
  <div class='diaPadding'>
    <el-tabs @tab-click='handleClick'>
      <el-tab-pane label='本地上传'>
        <div class='diaCon localUpdate'>
          <div v-if='!fileArr.length'>
            <el-upload
              drag
              action=''
              multiple
              :show-file-list='false'
              :http-request='requestUpload'
              :before-upload='beforeUpload'
              :limit='5'
              :on-exceed='onExceed'
            >
              <el-icon class='el-icon--upload'>
                <upload-filled />
              </el-icon>
              <div class='el-upload__text'>
                拖拽到区域上传或 <em>点击上传</em><br /><span>（请上传小于200M的文件）</span>
              </div>
            </el-upload>

          </div>
          <div class='filelist' v-else>
            <div class='row top'>
              <div class='item'>文件名</div>
              <div class='item'>大小</div>
              <div class='item'>状态</div>
              <div class='item'>操作</div>
            </div>
            <div class='row' v-for='(item,index) in fileArr' :key='item.uid'>
              <div class='item'>
                <svg class='coloricon' aria-hidden='true'>
                  <use :xlink:href="'#' + getFileIcon(item.fileRow.name)"></use>
                </svg>
                {{ giveEllipsisStr(item.fileRow.name, 35) }}
              </div>
              <div class='item'>{{ filterSize(item.fileRow.size) }}</div>
              <div class='item'>
                <div class='progress'>
                  <div class='line' :style="{ width: item.prss + '%' }"></div>
                </div>
                <div class='num'>{{ item.prss }}%</div>
              </div>
              <div class='item' @click='clickDelFile(index,item.cpt)'>
                <span class='iconfont icon-ashbin-fill'></span>
              </div>
            </div>


            <div>
              <el-upload
                action='#'
                multiple
                :http-request='requestUpload'
                :show-file-list='false'
                :before-upload='beforeUpload'
                :limit='5'
                :on-exceed='onExceed'
              >
                <div class='btnadding'>继续添加</div>
              </el-upload>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label='班课资料' v-if='isTeach()'>
        <div class='diaCon'>
          <div class='filelist2' v-loading='loading'>
            <div class='row top'>
              <div class='item'>选择</div>
              <div class='item'>文件名</div>
              <div class='item'>大小</div>
              <div class='item'>上传时间</div>
            </div>

            <div class='row' v-for='(item,index) in materArr' :key='item.id'>
              <div class='item'>
                <el-checkbox v-model='item.checked' size='large' @change='selfFileChange(index)' />
              </div>
              <div class='item'>{{ giveEllipsisStr(item.name, 40) }}</div>
              <div class='item'>{{ filterSize(item.byteCount) }}</div>
              <div class='item'>{{ parseTime(item.createTime) }}</div>
            </div>

          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label='公共资料库' v-if='isTeach()'>
        <div class='diaCon'>
          <el-empty description='开发中，待开放...' />
        </div>
      </el-tab-pane>
    </el-tabs>


  </div>
</template>

<script setup>
import { createOss } from '@/utils/alioss.js';
import { getFileID, materialList } from '@/api/banke/class';
import { getFileIcon, filterSize, getFilePath, getFileName, giveEllipsisStr, parseTime } from '@/utils/common';
import { ElMessage } from 'element-plus';
import { isTeach} from '@/utils/auth';
import {UploadFilled} from "@element-plus/icons-vue";

const fileNum = ref(5);
const fileArr = ref([]);
const bigFileArr = ref([]);
const materArr = ref([]);
const selfSelectArr = ref([]);
const loading = ref(true);
const cancelState = ref(false);
const maxSize = 200 * 1024 * 1024;
const props = defineProps({
  bigCfmState: {
    type: Boolean,
    default: true,
  },
});

const emits = defineEmits(['update:bigCfmState']);


//点击标签页按钮
const handleClick = (e) => {
  if (e.index == 1) {
    getMaterial();
  }
};


//获取个人班课资料库
const getMaterial = (keyname = '') => {
  materialList({ id: sessionStorage.getItem('bkid'), name: keyname }).then((res) => {

      if (res.code == 200) {
        materArr.value = res.rows;
        loading.value = false;
      } else {
        ElMessage.error('获取错误，请刷新');
      }
    },
  );
};

//点击自己课程资料库复选框
const selfFileChange = (index) => {
  let row = materArr.value[index];
  if (materArr.value[index].checked) {
    selfSelectArr.value.push({ ossId: row.ossId, customName: row.name });
  } else {
    selfSelectArr.value.forEach((i, idx) => {
      if (i.ossId == row.ossId) {
        selfSelectArr.value.splice(idx, 1);
      }
    });
  }
};

//监听自己资料的数组变化
watch(selfSelectArr.value, (nv, ov) => {
  if (nv.length > 0 || ov.length > 0) {
    emits('update:bigCfmState', false);
  }
});


/** 覆盖默认上传行为 */
function requestUpload() {
}

// 上传前处理
const beforeUpload = (file) => {
  emits('update:bigCfmState', true);
  if (file.size > maxSize) {
    ElMessage.error('文件超过200M，请压缩后再上传！！');
    return;
  }
  if (file.type.match(/image/i)) {
    ElMessage.error('大附件不允许上传图片类型！！');
    return;
  }
  cancelState.value = false;
  addZiLiao(getFilePath() + getFileName(file.name), file);
};


const addZiLiao = async (filename, file) => {

  let optionsOne = { byteCount: file.size, customName: file.name };
  let obj = { fileRow: file, cpt: null, prss: 0, oClient: await createOss() };
  if (cancelState.value) {
    return;
  }
  fileArr.value.push(obj);
  let upload = null;
  if (file.size > 1024 * 1024) {
    upload = await obj.oClient.multipartUpload(filename, file, {
      parallel: 3,
      partSize: 1024 * 1024,
      progress: (p, cpt) => {
        fileArr.value.forEach((item) => {
          if (item.fileRow.uid == file.uid) {
            item.prss = parseInt(p * 100);
            item.cpt = { name: cpt.name, uploadId: cpt.uploadId, prss: item.prss, customName: file.name };
          }
        });
      },
    });
    optionsOne.fileName = upload.name;
    optionsOne.originalName = upload.name;
    let requrl = upload.res.requestUrls[0];
    let index = requrl.lastIndexOf('?');
    if (index != -1) {
      requrl = requrl.substring(0, index);
    }
    optionsOne.url = requrl;

  } else {

    upload = await obj.oClient.put(filename, file);
    fileArr.value.forEach(item => {
      if (item.fileRow.uid == file.uid) {
        item.prss = 100;
        item.cpt = { name: upload.name, prss: 100, customName: file.name };
      }
    });
    optionsOne.fileName = upload.name;
    optionsOne.originalName = upload.name;
    optionsOne.url = upload.url;
  }


  _getFileID(optionsOne, file.name);

};


watch(() => bigFileArr.value, (nv, ov) => {
  if (nv.length == 0 || fileArr.value.length == 0) {
    return;
  }
  if (nv.length == fileArr.value.length) {
    emits('update:bigCfmState', false);
  }
}, { deep: true, immediate: true });


//点击删除上传的文件
const clickDelFile = async (index, cpt) => {

  let oClient = fileArr.value[index].oClient;
  if (!cpt) {
    oClient.cancel();
  } else if (cpt.prss == 100) {
    let del = await oClient.delete(cpt.name);
    console.log(del);
    let idx = bigFileArr.value.findIndex(item => {
      return item.customName == cpt.customName;
    });
    bigFileArr.value.splice(idx, 1);
  } else {
    try {
      let abort = await oClient.abortMultipartUpload(cpt.name, cpt.uploadId);
      console.log(abort);
    } catch (err) {
      console.log(err);
    }
  }
  fileArr.value.splice(index, 1);
};


//点击取消
const clickCancelUpload = () => {
  console.log(fileArr.value);
  fileArr.value.forEach((item, index) => {
    clickDelFile(index, item.cpt);
  });
};


//获取上传成功后的id
const _getFileID = (options, filename) => {
  getFileID(options).then((res) => {
    if (cancelState.value) {
      return;
    }
    bigFileArr.value.push({ ossId: res.data, customName: filename, byteCount: options.byteCount, url: options.url });
    console.log(bigFileArr.value);
  });
};


//超出上传限制
const onExceed = (e) => {
  if (e.length > fileNum.value) {
    ElMessage.error('单次最多只能选择5个，请重新选择');
  }
};

defineExpose({
  bigFileArr,
  fileArr,
  selfSelectArr,
  clickCancelUpload,
  cancelState,
});


</script>

<style lang='scss' scoped>
.diaPadding {
  padding-bottom: 30px;

  .diaCon {
    height: 500px;
    padding: 20px;
    overflow: auto;

    .filelist {
      .btnadding {
        width: 100px;
        line-height: 30px;
        text-align: center;
        border: 1px solid #4395ff;
        color: #4395ff;
        font-size: 14px;
        margin: 0 auto;
        margin-top: 30px;
      }

      .row {
        display: flex;
        align-items: center;
        height: 50px;
        font-size: 15px;

        .item:nth-child(1) {
          width: 50%;
        }

        .item:nth-child(2) {
          width: 10%;
        }

        .item:nth-child(3) {
          width: 230px;
          display: flex;

          .progress {
            height: 6px;
            width: 170px;
            background: #eee;
            border-radius: 10px;
            position: relative;
            overflow: hidden;

            .line {
              width: 0%;
              height: 6px;
              background: #4395ff;
              position: absolute;
              top: 0;
              left: 0;
              transition: 0.3s;
            }
          }

          .num {
            width: 50px;
            font-size: 12px;
            padding-left: 5px;
          }
        }

        .item:nth-child(4) {
          width: calc(40% - 220px);
        }
      }


    }

    .filelist2 {
      .row {
        display: flex;
        align-items: center;
        height: 43px;
        font-size: 14px;
        border-bottom: 1px solid #efefef;

        &:hover {
          background: #fafafa;
        }

        .item:nth-child(1) {
          width: 7%;
        }

        .item:nth-child(2) {
          width: 53%;
        }

        .item:nth-child(3) {
          width: 15%;
        }

        .item:nth-child(4) {
          width: 25%;
        }
      }
    }


    .top {
      background: #f5f7fa;
      font-size: 13px;
      height: 40px;
    }

    .item {
      padding: 0 10px;
      display: flex;
      align-items: center;

      .iconfont {
        font-size: 20px;
        cursor: pointer;
      }

      .coloricon {
        font-size: 23px;
        margin-right: 5px;
      }
    }
  }
}
</style>
